import { getCatalogues, addCatalogue, renameCatalogue, moveCatalogue } from '../controller/catalogue'
import { resultWrapper } from '../util/common'
import { interceptor } from './interceptor'
import { filterTree } from '../util/tree'

export default app => {
  // 获得目录列表
  app.post('/catalogues', interceptor({
    isNeedLock: false,
    func: async (req, res) => {
      let data = await getCatalogues(req, res)
      if (req.body.isShowAllCatalogue) {
        let judgeCb
        if (req.body.mainId) {
          judgeCb = item => item.type === 1 && item.mainId !== req.body.mainId
        } else {
          judgeCb = item => item.type === 1
        }
        data = filterTree({
          tree: [data],
          judgeCb
        })
      } else {
        data = filterTree({
          tree: [data],
          judgeCb: item => !item.label.endsWith(`.css`)
        })
      }
      res.send(resultWrapper(data))
    }
  }))
  
  // 新增目录
  app.post('/catalogue/add', interceptor({
    isNeedLock: true,
    func: async (req, res) => {
      let {data, message} = await addCatalogue(req, res)
      res.send(resultWrapper(data, message))
      return data
    }
  }))
  
  // 更改目录名称
  app.post('/catalogue/rename', interceptor({
    isNeedLock: true,
    func: async (req, res) => {
      let {data, message} = await renameCatalogue(req, res)
      res.send(resultWrapper(data, message))
      return data
    }
  }))
  
  // 移动目录
  app.post('/catalogue/move', interceptor({
    isNeedLock: true,
    func: async (req, res) => {
      let {data, message} = await moveCatalogue(req, res)
      res.send(resultWrapper(data, message))
      return data
    }
  }))
}
